<template>
  <div class="layoutCon">
    <div class="layoutCV">
      <div :class="['cvLeft',isFly&&'fly']">
        <div class="wap">
          <el-button class="btnBack2" @click="dialogVisible=true">목록으로</el-button>
          <div class="btns2">
            <el-button class="esc" :loading="frmLoading1" @click="submitForm(0)">임시저장</el-button>
            <el-button type="primary" :loading="frmLoading2" @click="submitForm(1)">저장하기</el-button>
          </div>
        </div>
        <el-button class="btnBack" @click="dialogVisible=true">목록으로</el-button>
        <div class="card">
            <div class="info">
                <div class="avatar" @click="showAvatarEdit"><img :src="userInfo&&userInfo.uthumb?userInfo.uthumb:defaultAvatar" alt="" :onerror="errorAvatar"></div>
                <div class="name">
                    <b>{{userInfo&&userInfo.name}}</b>
                    <span>{{formatBirthday()}}</span>
                </div>
                <div class="contact">
                    <span>{{userInfo&&userInfo.email}}</span>
                    <span>{{userInfo&&userInfo.phone}}</span>
                </div>
            </div>
        </div>
        <div class="steps" id="steps">
          <div class="scroll">
            <ul>
                <li :class="step==index&&'active'" v-for="(item,index) in steps" :key="index" @click="changeStep(index)">{{item}}</li>
            </ul>
          </div>
        </div>
        <div class="btns">
            <el-button class="esc" :loading="frmLoading1" @click="submitForm(0)">임시저장</el-button>
            <el-button type="primary" :loading="frmLoading2" @click="submitForm(1)">{{isCreat?'저장하기':'수정하기'}}</el-button>
        </div>
        <el-dialog class="dialogMini" title="목록으로" :closeOnClickModal="false" :visible.sync="dialogVisible">
          <div class="con">이전 화면으로 이동하시겠습니까?</div>
          <div slot="footer" class="miniFooter">
            <el-button type="primary" @click="backCV">확인</el-button>
            <el-button class="esc" @click="dialogVisible = false">취소</el-button>
          </div>
        </el-dialog>
        <avatar-edit></avatar-edit>
      </div>
      <div class="cvFrm">
        <div class="frmStep" v-show="step==0">
          <el-form :model="frm1" :rules="rules1" ref="frm1">
            <h1 class="mTit">지원정보</h1>
            <el-form-item prop="title">
              <div class="tit">
                  <label>이 이력서의 이름을 지어주세요.</label>
                  <span><em>Tip.</em> 직무별, 회사별로 제목을 구분하여 편리하게 관리하세요. 이력서에 표시되지 않습니다.</span>
              </div>
              <el-input placeholder="이력서 제목" v-model="frm1.title"></el-input>
            </el-form-item>
            <el-form-item prop="application_scope">
              <div class="tit">
                  <label>지원분야를 작성해주세요.</label>
                  <span><em>Tip.</em> 채용담당자에게 노출될 지원분야입니다.</span>
              </div>
              <el-input placeholder="예시) IT 전문가, 사무직, 마케팅, 영업 등" v-model="frm1.application_scope"></el-input>
            </el-form-item>
            <el-form-item prop="experts_type">
              <div class="tit">
                  <label>어떤 전문가가 되고 싶으세요?</label>
                  <span><em>Tip.</em> 도전하는 마케터, 신사업 전략가 등 나를 나타내는 말과 직업명을 합쳐 멋진 별명을 만들어 보세요.</span>
              </div>
              <el-input placeholder="예시) 도전하는 마케터, 신사업 전략가" v-model="frm1.experts_type"></el-input>
            </el-form-item>
            <div class="tit">
                <label>희망직무를 선택해주세요. (최대5개)</label>
            </div>
            <div class="selectItem" v-for="(item,index) in frm1.jobs" :key="item.index">
              <div class="selects">
                <el-form-item class="mb" :prop="`jobs.${index}.value`"
                  :rules="{required: true, message: '직무를 선택하세요', trigger: 'change'}"
                >
                  <el-cascader popper-class="myCascader" v-model="item.value" placeholder="직무를 선택하세요" :options="jobList" :props="{ checkStrictly: true }" separator=" > " clearable @change="changeJobs($event,index)"></el-cascader>
                </el-form-item>
                <el-button :disabled="frm1.jobs.length==1?true:false" @click="removeJob(item)" class="btnDel"></el-button>
              </div>
            </div>
            <div class="btn mb">
                <el-button v-if="frm1.jobs.length<5" @click="addJob">추가하기</el-button>
            </div>
            <div class="tit">
                <label>희망근무지역을 선택하세요. (최대5개)</label>
            </div>
            <div class="selectItem" v-for="(item,index) in frm1.areas" :key="item.index">
              <div class="selects">
                  <el-form-item class="mb" :prop="`areas.${index}.value`"
                    :rules="{required: true, message: '희망근무지역을 선택하세요', trigger: 'change'}"
                  >
                    <el-cascader popper-class="myCascader2" v-model="item.value" placeholder="희망근무지역을 선택하세요" :options="areaList" :props="{ checkStrictly: true }" separator=" > " clearable @change="changeArea($event,index)"></el-cascader>
                  </el-form-item>
                  <el-button :disabled="frm1.areas.length==1?true:false" @click="removeAreas(item)" class="btnDel"></el-button>
              </div>
            </div>
            <div class="btn mb">
                <el-button v-if="frm1.areas.length<5" @click="addAreas">추가하기</el-button>
            </div>
            <el-form-item prop="introduce">
              <div class="tit">
                  <label>기업 인사담당자에게 나를 소개해 봅시다.</label>
                  <span><em>Tip.</em> 성격, 마음가짐 등 일에 대한 열정을 어필할 수 있는 내용이 좋아요.</span>
              </div>
              <summernote @checkCon="checkCon"></summernote>
            </el-form-item>
            <el-form-item>
              <div class="tit">
                  <label>컴퓨터 활용은 기본 중의 기본!</label>
                  <span><em>Tip.</em> OA 스킬 점수를 스스로 매겨보세요. 실제 능력보다 높게 선택하는 것이 무조건 좋지는 않습니다.</span>
              </div>
              <div class="oaList">
                  <ul>
                      <li>
                          <div class="name"></div>
                          <div class="size">
                              <span>어려움</span>
                              <span>중간</span>
                              <span>능숙함</span>
                          </div>
                      </li>
                      <li v-for="(item,index) in oaList" :key="index">
                          <div class="name">{{item.name}}</div>
                          <el-slider v-model="item.value" :max="10" :show-tooltip="false" @change="gradeChange($event,item.tag)"></el-slider>
                      </li>
                  </ul>
              </div>
            </el-form-item>
            <el-form-item prop="keywords">
              <div class="tit">
                  <label>내 이력서를 키워드로 요약해 본다면?</label>
                  <span><em>Tip.</em> 내 이력서가 한 눈에 들어오도록 키워드를 입력해 주세요. 키워드는 쉼표(,)로 구분합니다.</span>
              </div>
              <el-input placeholder="예시) 전략, 해외사업, 기획, 변화관리, 리스크 관리 등등" v-model="frm1.keywords"></el-input>
            </el-form-item>
            <el-form-item>
              <div class="tit">
                  <label>공개여부</label>
                  <span><em>Tip.</em> 이력서를 공개하시면 채용담당자가 나의 이력서를 확인 할 수 있습니다.</span>
              </div>
              <el-radio-group v-model="frm1.is_public">
                  <el-radio-button label="0">비공개</el-radio-button>
                  <el-radio-button label="1">공개</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
        <div class="frmStep" v-show="step==1">
          <el-form :model="frm2" ref="frm2">
            <h1 class="mTit">핵심역량</h1>
            <div class="innerBox" v-for="(item,index) in frm2.skills">
              <el-form-item
                :key="item.index"
                :prop="`skills.${index}.skill`"
                :rules="{
                  required: true, message: '핵심역량을 작성해주세요.', trigger: 'blur'
                }"
              >
                  <div class="tit">
                      <label>지원분야에 어떤 핵심역량이 있으세요?</label>
                      <span><em>Tip.</em> 간결하게 정리해 주세요. 나의 역량을 표현하는 소제목이 됩니다.</span>
                  </div>
                  <el-input placeholder="예시) 영업 시스템 구축, 신규 유통망 개발과 매출을 키우는 전문 영업 등" v-model="item.skill"></el-input>
              </el-form-item>
              <el-form-item
                :key="item.index"
                :prop="`skills.${index}.experience`"
                :rules="{
                  required: true, message: '업무 경험을 이력해주세요.', trigger: 'blur'
                }"
              >
                  <div class="tit">
                      <label>핵심역량이 드러나는 수행한 업무와 경험을 적어주세요.</label>
                      <span><em>Tip.</em> 구체적으로 어떠한 일을 하여, 어떠한 성과를 이루어 내었는지 정량적인 근거를 바탕으로 작성해 주세요.</span>
                  </div>
                  <el-input type="textarea" :rows="10" v-model="item.experience"></el-input>
              </el-form-item>
              <div class="btn">
                  <el-button :disabled="frm2.skills.length==1?true:false" @click="removeSkill(item)">삭제하기</el-button>
              </div>
            </div>
            <div class="longBtn">
                <el-button type="primary" @click="addSkill">+ 핵심역량 추가</el-button>
            </div>
          </el-form>
        </div>
        <div class="frmStep" v-show="step==2">
          <el-form :model="frm3" ref="frm3">
            <h1 class="mTit">경력</h1>
<!--            <div class="comTips">전체 경력 중 대표직무 2개 입력 (1개 필수)</div>-->
            <div class="innerBox" v-for="(item,index) in frm3.experiences">
                <el-form-item
                  :key="item.index"
                  :prop="`experiences.${index}.company`"
                  :rules="{
                    required: true, message: '기업명을 입력해주세요.', trigger: 'blur'
                  }"
                >
                    <div class="tit">
                        <label>기업명</label>
                    </div>
                    <el-input placeholder="" v-model="item.company"></el-input>
                </el-form-item>
                <el-form-item
                  :key="item.index"
                  :prop="`experiences.${index}.department`"
                  :rules="{
                    required: true, message: '팀명을 입력해주세요.', trigger: 'blur'
                  }"
                >
                    <div class="tit">
                        <label>팀명</label>
                    </div>
                    <el-input placeholder="" v-model="item.department"></el-input>
                </el-form-item>
                <el-form-item
                  :key="item.index"
                  :prop="`experiences.${index}.start_at`"
                  :rules="{
                    required: true, validator: validateExp, trigger: 'change'
                  }"
                >
                    <div class="tit">
                        <label>재직기간</label>
                    </div>
                    <el-date-picker
                      class="cvDataPicker small"
                      v-model="item.start_at"
                      :picker-options="pickerOptions"
                      type="month"
                      :editable="false"
                      value-format="yyyy-MM"
                      placeholder="시작 월">
                    </el-date-picker>
                    <div class="separator"></div>
                    <el-date-picker
                      class="cvDataPicker small"
                      v-model="item.end_at"
                      :picker-options="pickerOptions"
                      type="month"
                      :editable="false"
                      value-format="yyyy-MM"
                      placeholder="종료 월">
                    </el-date-picker>
                </el-form-item>
                <el-form-item
                  :key="item.index"
                  :prop="`experiences.${index}.duty`"
                  :rules="{
                    required: true, message: '직책을 입력해주세요.', trigger: 'blur'
                  }"
                >
                    <div class="tit">
                        <label>직책</label>
                    </div>
                    <el-input placeholder="" v-model="item.duty"></el-input>
                </el-form-item>
                <el-form-item
                  :key="item.index"
                  :prop="`experiences.${index}.job_content`"
                  :rules="{
                    required: true, message: '경력내용을 입력해주세요.', trigger: 'blur'
                  }"
                >
                    <div class="tit">
                        <label>경력내용</label>
                        <span><em>Tip.</em> 전체 경력 중 대표직무 1~2개를 간략하게 요약해 주세요.</span>
                    </div>
                    <el-input type="textarea" :rows="6" v-model="item.job_content"></el-input>
                </el-form-item>
                <div class="btn">
                    <el-button :disabled="frm3.experiences.length==1?true:false" @click="removeExp(item)">삭제하기</el-button>
                </div>
            </div>
            <div class="longBtn">
                <el-button type="primary" @click="addExp">+ 경력 추가</el-button>
            </div>
          </el-form>
        </div>
        <div class="frmStep" v-show="step==3">
          <el-form :model="frm4" ref="frm4">
            <h1 class="mTit">학력</h1>
            <div class="comTips">최종학력부터 작성하세요.</div>
            <div class="innerBox" v-for="(item,index) in frm4.educations">
                <el-form-item
                  :key="item.index"
                  :prop="`educations.${index}.school`"
                  :rules="{
                    required: true, message: '학교명을 입력해주세요.', trigger: 'blur'
                  }"
                >
                    <div class="tit">
                        <label>학교명</label>
                    </div>
                    <el-input placeholder="" v-model="item.school"></el-input>
                </el-form-item>
                <el-form-item
                  :key="item.index"
                  :prop="`educations.${index}.status`"
                  :rules="{
                    required: true, message: '상태를 선택해주세요.', trigger: 'change'
                  }"
                >
                    <div class="tit">
                        <label>상태</label>
                    </div>
                    <el-select placeholder="선택" v-model="item.status">
                        <el-option label="졸업" :value="0"></el-option>
                        <el-option label="재학" :value="1"></el-option>
                        <el-option label="휴학" :value="2"></el-option>
                        <el-option label="수료" :value="3"></el-option>
                        <el-option label="중퇴" :value="4"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item
                  :key="item.index"
                  :prop="`educations.${index}.end_at`"
                  :rules="{
                    required: true, message: '졸업년월을 선택해주세요.', trigger: 'blur'
                  }"
                >
                    <div class="tit">
                        <label>졸업년월</label>
                    </div>
                    <el-date-picker
                      class="cvDataPicker small"
                      v-model="item.end_at"
                      type="month"
                      :editable="false"
                      value-format="yyyy-MM-dd"
                      placeholder="졸업년월">
                    </el-date-picker>
                </el-form-item>
                <el-form-item
                  :key="item.index"
                  :prop="`educations.${index}.specialities`"
                  :rules="{
                    required: true, message: '전공명을 입력해주세요.', trigger: 'blur'
                  }"
                >
                    <div class="tit">
                        <label>전공명</label>
                    </div>
                    <el-input placeholder="" v-model="item.specialities"></el-input>
                </el-form-item>
                <div class="btn">
                    <el-button :disabled="frm4.educations.length==1?true:false" @click="removeEducation(item)">삭제하기</el-button>
                </div>
            </div>
            <div class="longBtn">
                <el-button type="primary" @click="addEducation">+ 학력 추가</el-button>
            </div>
          </el-form>
        </div>
        <div class="frmStep" v-show="step==4">
          <el-form :model="frm5" ref="frm5">
            <h1 class="mTit">교육</h1>
            <div class="comTips">최근 교육부터 작성하세요.</div>
            <div class="innerBox" v-for="(item,index) in frm5.trains">
                <el-form-item
                  :key="item.index"
                  :prop="`trains.${index}.training`"
                  :rules="{
                    required: true, message: '교육명을 입력해주세요.', trigger: 'blur'
                  }"
                >
                    <div class="tit">
                        <label>교육명</label>
                    </div>
                    <el-input placeholder="" v-model="item.training"></el-input>
                </el-form-item>
                <el-form-item
                  :key="item.index"
                  :prop="`trains.${index}.training_organization`"
                  :rules="{
                    required: true, message: '교육기관을 입력해주세요.', trigger: 'blur'
                  }"
                >
                    <div class="tit">
                        <label>교육기관</label>
                    </div>
                    <el-input placeholder="" v-model="item.training_organization"></el-input>
                </el-form-item>
                <el-form-item
                  :key="item.index"
                  :prop="`trains.${index}.start_at`"
                  :rules="{
                    required: true, validator: validateTrains, trigger: 'change'
                  }"
                >
                    <div class="tit">
                        <label>교육기간</label>
                    </div>
                    <el-date-picker
                      class="cvDataPicker small"
                      v-model="item.start_at"
                      :picker-options="pickerOptions"
                      type="month"
                      :editable="false"
                      value-format="yyyy-MM"
                      placeholder="시작 월">
                    </el-date-picker>
                    <div class="separator"></div>
                    <el-date-picker
                      class="cvDataPicker small"
                      v-model="item.end_at"
                      :picker-options="pickerOptions"
                      type="month"
                      :editable="false"
                      value-format="yyyy-MM"
                      placeholder="종료 월">
                    </el-date-picker>
                </el-form-item>
                <div class="btn">
                    <el-button :disabled="frm5.trains.length==1?true:false" @click="removeTrains(item)">삭제하기</el-button>
                </div>
            </div>
            <div class="longBtn">
                <el-button type="primary" @click="addTrains">+ 교육 추가</el-button>
            </div>
          </el-form>
        </div>
        <div class="frmStep" v-show="step==5">
          <el-form :model="frm6" ref="frm6">
            <h1 class="mTit">수상이력</h1>
            <div class="comTips">최근 수상이력부터 작성하세요.</div>
            <div class="innerBox" v-for="(item,index) in frm6.awards">
                <el-form-item
                  :key="item.index"
                  :prop="`awards.${index}.award_name`"
                  :rules="{
                    required: true, message: '수상명을 입력해 주세요.', trigger: 'blur'
                  }"
                >
                    <div class="tit">
                        <label>수상명</label>
                    </div>
                    <el-input placeholder="" v-model="item.award_name"></el-input>
                </el-form-item>
                <el-form-item
                  :key="item.index"
                  :prop="`awards.${index}.award_desc`"
                  :rules="{
                    required: true, message: '수상내용을 입력해주세요.', trigger: 'blur'
                  }"
                >
                    <div class="tit">
                        <label>수상내용</label>
                    </div>
                    <el-input placeholder="" v-model="item.award_desc"></el-input>
                </el-form-item>
                <el-form-item
                  :key="item.index"
                  :prop="`awards.${index}.issued_by`"
                  :rules="{
                    required: true, message: '수여기관을 입력해 주세요.', trigger: 'blur'
                  }"
                >
                    <div class="tit">
                        <label>수여기관</label>
                    </div>
                    <el-input placeholder="" v-model="item.issued_by"></el-input>
                </el-form-item>
                <el-form-item
                  :key="item.index"
                  :prop="`awards.${index}.get_at`"
                  :rules="{
                    required: true, message: '수상년도를 선택해주세요.', trigger: 'blur'
                  }"
                >
                    <div class="tit">
                        <label>수상년도</label>
                    </div>
                    <el-date-picker
                      class="cvDataPicker small"
                      v-model="item.get_at"
                      type="year"
                      :editable="false"
                      :picker-options="pickerOptions"
                      value-format="yyyy"
                      placeholder="연도선택">
                    </el-date-picker>
                </el-form-item>
                <div class="btn">
                    <el-button :disabled="frm6.awards.length==1?true:false" @click="removeAwards(item)">삭제하기</el-button>
                </div>
            </div>
            <div class="longBtn">
                <el-button type="primary" @click="addAwards">+ 수상이력 추가</el-button>
            </div>
          </el-form>
        </div>
        <div class="frmStep" v-show="step==6">
          <el-form :model="frm7" ref="frm7">
            <h1 class="mTit">자격증</h1>
            <div class="comTips">최근 취득 자격증부터 작성하세요.</div>
            <div class="innerBox" v-for="(item,index) in frm7.certifieds">
                <el-form-item
                  :key="item.index"
                  :prop="`certifieds.${index}.certified`"
                  :rules="{
                    required: true, message: '자격증명을 입력해 주세요.', trigger: 'blur'
                  }"
                >
                    <div class="tit">
                        <label>자격증명</label>
                    </div>
                    <el-input placeholder="" v-model="item.certified"></el-input>
                </el-form-item>
                <el-form-item
                  :key="item.index"
                  :prop="`certifieds.${index}.grade`"
                  :rules="{
                    required: false, message: '자격증 등급을 입력해주세요.', trigger: 'blur'
                  }"
                >
                    <div class="tit">
                        <label>등급</label>
                    </div>
                    <el-input placeholder="" v-model="item.grade"></el-input>
                </el-form-item>
                <el-form-item
                  :key="item.index"
                  :prop="`certifieds.${index}.issued_by`"
                  :rules="{
                    required: true, message: '취득기관을 입력해 주세요.', trigger: 'blur'
                  }"
                >
                    <div class="tit">
                        <label>취득기관</label>
                    </div>
                    <el-input placeholder="" v-model="item.issued_by"></el-input>
                </el-form-item>
                <el-form-item
                  :key="item.index"
                  :prop="`certifieds.${index}.get_at`"
                  :rules="{
                    required: true, message: '취득년도를 선택해주세요.', trigger: 'blur'
                  }"
                >
                    <div class="tit">
                        <label>취득년도</label>
                    </div>
                    <el-date-picker
                      class="cvDataPicker small"
                      v-model="item.get_at"
                      type="year"
                      :editable="false"
                      :picker-options="pickerOptions"
                      value-format="yyyy"
                      placeholder="연도선택">
                    </el-date-picker>
                </el-form-item>
                <div class="btn">
                    <el-button :disabled="frm7.certifieds.length==1?true:false" @click="removeCertifieds(item)">삭제하기</el-button>
                </div>
            </div>
            <div class="longBtn">
                <el-button type="primary" @click="addCertifieds">+ 자격증 추가</el-button>
            </div>
          </el-form>
        </div>
        <div class="frmBom">
            <el-button class="pre" v-if="step>0" @click="back">{{steps[step-1]}}</el-button>
            <el-button class="next" v-if="step<6" @click="next">{{steps[step+1]}}</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import { jobOption, areaList, myCreateCv, myEditCv, getCVDetail, educationLevel } from '@/api';
import avatarEdit from '@/components/avatarEdit'
import Summernote from '@/components/summernote'

export default {
  name:'',
  components:{Summernote,avatarEdit},
  props:[],
  data(){
    return {
      frmLoading1:false,
      frmLoading2:false,
      dialogVisible:false,
      isFly:false,
      scrollNum:0,
      isCreat:false,
      step:0,
      steps:['지원정보','핵심역량','경력','학력','교육','수상이력','자격증'],
      cv_id:0,
      jobList:[],
      areaList:[],
      oaList:[
          {id:1,name:'파워포인트',value:0,tag:'PPT_grade'},
          {id:2,name:'Excel',value:0,tag:'Excel_grade'},
          {id:3,name:'Word',value:0,tag:'Word_grade'},
          {id:4,name:'아래한글',value:0,tag:'HWP_grade'},
      ],
      levels:[],
      pickerOptions:{
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      frm1:{
          status:0,
          title:'',
          application_scope:'',
          experts_type:'',
          PPT_grade:0,
          Excel_grade:0,
          Word_grade:0,
          HWP_grade:0,
          introduce:'',
          keywords:'',
          is_public:0,
          jobs:[
            {job1_id:'',job2_id:'',job3_id:'',value:[]}
          ],
          areas:[
            {area1_id:'',area2_id:'',area3_id:'',value:[]}
          ],
          skills:[
            {skill:'',experience:''}
          ],
      },
      rules1:{
        title: [
          { required: true, message: '이력서 제목을 입력해주세요.', trigger: 'blur' }
        ],
        application_scope: [
          { required: true, message: '지원분야를 작성해주세요.', trigger: 'blur' }
        ],
        experts_type: [
          { required: true, message: '되고 싶은 전문가를 입력해주세요.', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '자기소개를 입력해주세요.', trigger: 'blur' }
        ],
        keywords: [
          { required: true, message: '키워드를 입력해 주세요.', trigger: 'blur' }
        ],
      },
      frm2:{
        skills:[
          {skill:'',experience:''}
        ],
      },
      frm3:{
        experiences:[
          {
            company:'',
            department:'',
            start_at:'',
            end_at:'',
            duty:'',
            job_content:''
          }
        ]
      },
      frm4:{
        educations:[
          {
            school:'',
            status:'',
            end_at:'',
            specialities:''
          }
        ]
      },
      frm5:{
        oldFrmData:null,
        trains:[
          {
            training:'',
            training_organization:'',
            start_at:'',
            end_at:''
          }
        ]
      },
      frm6:{
        oldFrmData:null,
        awards:[
          {
            award_name:'',
            award_desc:'',
            issued_by:'',
            get_at:''
          }
        ]
      },
      frm7:{
        oldFrmData:null,
        certifieds:[
          {
            certified:'',
            issued_by:'',
            get_at:'',
            grade:''
          }
        ]
      },
      isComplete:false,
      oldResumeData:null,
      oldFrmData:null
    }
  },
  computed:{
    ...mapState(['userInfo','role','anchor','errorAvatar','defaultAvatar'])
  },
  created(){
    this.cv_id=this.$route.query.cv_id||0;
    if(this.cv_id){
      this.getCVInfo();
    }else{
      this.frm5.oldFrmData=JSON.stringify(this.frm5.trains);
      this.frm6.oldFrmData=JSON.stringify(this.frm6.awards);
      this.frm7.oldFrmData=JSON.stringify(this.frm7.certifieds);
    }
    this.getJobOption()
    this.getAreaList()

    let _type=this.$route.query.type||0;
    _type=='new'&&(this.isCreat=true);

  },
  mounted(){
    if (window.history && window.history.pushState) {
      history.pushState(null, null, document.URL);
      window.addEventListener('popstate', this.goBack, false);
    }
    window.addEventListener('scroll', this.handleScroll)
  },
  methods:{
    ...mapActions(['setShowAvatarEdit']),
    async submitForm(type) {
      let _this=this,_frmParams={},
          isPass1=false,isPass2=false,isPass3=false,isPass4=false,isPass5=false,isPass6=false,isPass7=false;
      _frmParams.status=type;
      let _frm5New=JSON.stringify(_this.frm5.trains),
          _frm6New=JSON.stringify(_this.frm6.awards),
          _frm7New=JSON.stringify(_this.frm7.certifieds);
      this.frm1.introduce=$('#summernote').summernote('code');
      switch(this.step){
        case 0:
          _checkFrm1();
          isPass1&&_checkFrm2();
          isPass1&&isPass2&&_checkFrm3();
          isPass1&&isPass2&&isPass3&&_checkFrm4();
          isPass1&&isPass2&&isPass3&&isPass4&&_checkOther();
          break;
        case 1:
          _checkFrm2();
          isPass2&&_checkFrm1();
          isPass1&&isPass2&&_checkFrm3();
          isPass1&&isPass2&&isPass3&&_checkFrm4();
          isPass1&&isPass2&&isPass3&&isPass4&&_checkOther();
          break;
        case 2:
          _checkFrm3();
          isPass3&&_checkFrm1();
          isPass1&&isPass3&&_checkFrm2();
          isPass1&&isPass2&&isPass3&&_checkFrm4();
          isPass1&&isPass2&&isPass3&&isPass4&&_checkOther();
          break;
        case 3:
          _checkFrm4();
          isPass4&&_checkFrm1();
          isPass1&&isPass4&&_checkFrm2();
          isPass1&&isPass2&&isPass4&&_checkFrm3();
          isPass1&&isPass2&&isPass3&&isPass4&&_checkOther();
          break;
        case 4:
          if(_frm5New!==_this.frm5.oldFrmData){
            _checkFrm5();
            isPass5&&_checkNeed();
          }else{
            _checkNeed();
          }
          break;
        case 5:
          if(_frm6New!==_this.frm6.oldFrmData){
            _checkFrm6();
            isPass6&&_checkNeed();
          }else{
            _checkNeed();
          }
          break;
        case 6:
          if(_frm7New!==_this.frm7.oldFrmData){
            _checkFrm7();
            isPass7&&_checkNeed();
          }else{
            _checkNeed();
          }
          break;
      }
      function _checkNeed(){
        _checkFrm1();
        isPass1&&_checkFrm2();
        isPass1&&isPass2&&_checkFrm3();
        isPass1&&isPass2&&isPass3&&_checkFrm4();
        isPass1&&isPass2&&isPass3&&isPass4&&_checkOther();
      }
      function _checkOther(){
        if(_frm5New!==_this.frm5.oldFrmData&&!isPass5){
          _checkFrm5();
        }else if(_frm6New!==_this.frm6.oldFrmData&&!isPass6){
          _checkFrm6();
        }else if(_frm7New!==_this.frm7.oldFrmData&&!isPass7){
          _checkFrm7();
        }
      }
      // check frm1
      function _checkFrm1(){
        _this.$refs.frm1.validate( (valid,error) => {
          if (valid) {
            let _areas=[],_jobs=[]
            _this.frm1.areas.forEach((o,i)=>{
              let _item={};
                  o.area1_id&&(_item.area1_id=o.area1_id)
                  o.area2_id&&(_item.area2_id=o.area2_id)
                  o.area3_id&&(_item.area3_id=o.area3_id)
                  _areas.push(_item)
            })
            _this.frm1.jobs.forEach((o,i)=>{
              let _item={};
                  o.job1_id&&(_item.job1_id=o.job1_id)
                  o.job2_id&&(_item.job2_id=o.job2_id)
                  o.job3_id&&(_item.job3_id=o.job3_id)
                  _jobs.push(_item)
            })

            _frmParams.title=_this.frm1.title;
            _frmParams.application_scope=_this.frm1.application_scope;
            _frmParams.experts_type=_this.frm1.experts_type;
            _frmParams.PPT_grade=_this.frm1.PPT_grade;
            _frmParams.Excel_grade=_this.frm1.Excel_grade;
            _frmParams.Word_grade=_this.frm1.Word_grade;
            _frmParams.HWP_grade=_this.frm1.HWP_grade;
            _frmParams.introduce=_this.frm1.introduce;
            _frmParams.keywords=_this.frm1.keywords;
            _frmParams.is_public=_this.frm1.is_public;
            _frmParams.jobs=JSON.stringify(_jobs);
            _frmParams.areas=JSON.stringify(_areas);

            isPass1=true;
          } else {
            isPass1=false;
            let _msg='작성하지 않은 항목이 있습니다. 다시 한번 확인해 주세요.';
            _this.step!=0&&(_msg='지원정보를 작성하지 않았습니다.')
            _this.$alert(_msg, '알림', {
              confirmButtonText: '확인',
              callback: action => {
                _this.step=0;
              }
            });
          }
        });
      }
      // check frm2
      function _checkFrm2(){
        _this.$refs.frm2.validate( (valid,error) => {
          if (valid) {
            _frmParams.skills=JSON.stringify(_this.frm2.skills);
            isPass2=true;
          }else{
            isPass2=false;
            let _msg='작성하지 않은 항목이 있습니다. 다시 한번 확인해 주세요.';
            _this.step!=1&&(_msg='핵심역량을 작성해주세요.')
            _this.$alert(_msg, '알림', {
              confirmButtonText: '확인',
              callback: action => {
                _this.step=1;
              }
            });
          }
        });
      }
      // check frm3
      function _checkFrm3(){
        _this.$refs.frm3.validate( (valid,error) => {
          if (valid) {
            let _arry=JSON.parse(JSON.stringify(_this.frm3.experiences));
            _frmParams.experiences=JSON.stringify(_arry);
            isPass3=true;
          }else{
            isPass3=false;
            let _msg='작성하지 않은 항목이 있습니다. 다시 한번 확인해 주세요.';
            _this.step!=2&&(_msg='근무경력을 작성해주세요.')
            _this.$alert(_msg, '알림', {
              confirmButtonText: '확인',
              callback: action => {
                _this.step=2;
              }
            });
          }
        });
      }
      // check frm4
      function _checkFrm4(){
        _this.$refs.frm4.validate( (valid,error) => {
          if (valid) {
            _frmParams.educations=JSON.stringify(_this.frm4.educations);
            isPass4=true;
          }else{
            isPass4=false;
            let _msg='작성하지 않은 항목이 있습니다. 다시 한번 확인해 주세요.';
            _this.step!=3&&(_msg='학력정보를 적어 주세요.')
            _this.$alert(_msg, '알림', {
              confirmButtonText: '확인',
              callback: action => {
                _this.step=3;
              }
            });
          }
        });
      }
      // check frm5
      function _checkFrm5(){
        _this.$refs.frm5.validate( (valid,error) => {
          if (valid) {
            let _arry=JSON.parse(JSON.stringify(_this.frm5.trains));
            if(_arry.length){
              _frmParams.trains=JSON.stringify(_arry);
            }
            isPass5=true;
            _checkOther();
          }else{
            isPass5=false;
            _this.$alert('작성하지 않은 항목이 있습니다. 다시 한번 확인해 주세요.', '알림', {
              confirmButtonText: '확인',
              callback: action => {
                _this.step=4;
              }
            });
          }
        });
      }
      // check frm6
      function _checkFrm6(){
        console.log(isPass6)
        _this.$refs.frm6.validate( (valid,error) => {
          if (valid) {
            _frmParams.awards=JSON.stringify(_this.frm6.awards);
            isPass6=true;
            _checkOther();
          }else{
            isPass6=false;
            _this.$alert('작성하지 않은 항목이 있습니다. 다시 한번 확인해 주세요.', '알림', {
              confirmButtonText: '확인',
              callback: action => {
                _this.step=5;
              }
            });
          }
        });
      }
      // check frm7
      function _checkFrm7(){
        _this.$refs.frm7.validate( (valid,error) => {
          if (valid) {
            _frmParams.certifieds=JSON.stringify(_this.frm7.certifieds);
            isPass7=true;
            _checkOther();
          }else{
            isPass7=false;
            _this.$alert('작성하지 않은 항목이 있습니다. 다시 한번 확인해 주세요.', '알림', {
              confirmButtonText: '확인',
              callback: action => {
                _this.step=6;
              }
            });
          }
        });
      }
      if(isPass1&&isPass2&&isPass3&&isPass4){
        if((_frm5New==_this.frm5.oldFrmData||(_frm5New!==_this.frm5.oldFrmData&&isPass5))&&(_frm6New==_this.frm6.oldFrmData||(_frm6New!==_this.frm6.oldFrmData&&isPass6))&&(_frm7New==_this.frm7.oldFrmData||(_frm7New!==_this.frm7.oldFrmData&&isPass7))){
          // submit frm
          if(type==0){
            this.frmLoading1=true;
            this.frmLoading2=false;
          }else{
            this.frmLoading1=false;
            this.frmLoading2=true;
          }
          if(this.cv_id){
            _frmParams.cv_id=this.cv_id;
            let res = await myEditCv(_frmParams);
            if(res.code==200){
              this.frmLoading1=false;
              this.frmLoading2=false;
              this.tips(type)
            }else{
              this.frmLoading1=false;
              this.frmLoading2=false;
            }
          }else{
            let res = await myCreateCv(_frmParams);
            if(res.code==200){
              this.frmLoading1=false;
              this.frmLoading2=false;
              this.tips(type)
            }else{
              this.frmLoading1=false;
              this.frmLoading2=false;
            }
          }
        }
      }
    },
    tips(type){
      let _msg=(type==0?'임시저장이 정삭적으로 완료되었습니다.':(this.isCreat?'저장 완료.':'수정이 완료되었습니다.'))
      this.$alert(_msg, '알림', {
        confirmButtonText: '확인',
        callback: action => {
          this.$router.replace('/my/cv')
        }
      });
    },
    // step1
    async getCVInfo(){
      let res = await getCVDetail({cv_id:this.cv_id});
      if(res.code==200){
        this.oldResumeData=res.data;
        let _data=res.data,_jobs=[],_areas=[];
        if(_data.jobs.length){
          _data.jobs.forEach((o,i)=>{
            let _item={job1_id:o.job1_id,job2_id:o.job2_id,job3_id:o.job3_id,value:[o.job1_id]}
            o.job2_id&&_item.value.push(o.job2_id)
            o.job3_id&&_item.value.push(o.job3_id)
            _jobs.push(_item)
          })
        }else{
          _jobs.push({job1_id:'',job2_id:'',job3_id:'',value:[]})
        }
        if(_data.areas.length){
          _data.areas.forEach((o,i)=>{
            let _item={area1_id:o.area1_id,area2_id:o.area2_id,area3_id:o.area3_id,value:[o.area1_id]}
              o.area2_id&&_item.value.push(o.area2_id)
              o.area3_id&&_item.value.push(o.area3_id)
            _areas.push(_item)
          })
        }else{
          _areas.push({area1_id:'',area2_id:'',area3_id:'',value:[]})
        }
        this.oaList[0].value=_data.PPT_grade;
        this.oaList[1].value=_data.Excel_grade;
        this.oaList[2].value=_data.Word_grade;
        this.oaList[3].value=_data.HWP_grade;

        this.frm1.status=_data.status;
        this.frm1.title=_data.title;
        this.frm1.application_scope=_data.application_scope;
        this.frm1.experts_type=_data.experts_type;
        this.frm1.PPT_grade=_data.PPT_grade;
        this.frm1.Excel_grade=_data.Excel_grade;
        this.frm1.Word_grade=_data.Word_grade;
        this.frm1.HWP_grade=_data.HWP_grade;
        this.frm1.introduce=_data.introduce;
        this.frm1.keywords=_data.keywords;
        this.frm1.is_public=_data.is_public;
        this.frm1.jobs=_jobs;
        this.frm1.areas=_areas;
        $('#summernote').summernote('code',_data.introduce);

        // step 2
        let _skills=[];
        if(_data.skills.length){
          _data.skills.forEach((o,i)=>{
            let _item={skill:o.skill,experience:o.experience}
            _skills.push(_item)
          })
        }
        this.frm2.skills=_skills.length?_skills:[{skill:'',experience:''}];

        // step3
        let _experiences=[];
        if(_data.experiences.length){
          _data.experiences.forEach((o,i)=>{
            let _item={
              company:o.company,
              department:o.department,
              start_at:o.start_at,
              end_at:o.end_at,
              duty:o.duty,
              job_content:o.job_content
            }
            _experiences.push(_item)
          })
          this.frm3.experiences=_experiences;
        }
        // step4
        let _educations=[];
        if(_data.educations.length){
          _data.educations.forEach((o,i)=>{
            let _item={
              school:o.school,
              status:o.status,
              end_at:o.end_at,
              specialities:o.specialities
            }
            _educations.push(_item)
          })
          this.frm4.educations=_educations;
        }
        // step5
        let _trains=[];
        if(_data.trains.length){
          _data.trains.forEach((o,i)=>{
            let _item={
              training:o.training,
              training_organization:o.training_organization,
              start_at:o.start_at,
              end_at:o.end_at
            }
            _trains.push(_item)
          })
          this.frm5.trains=_trains;
          this.frm5.oldFrmData=JSON.stringify(_trains);
        }else{
          this.frm5.oldFrmData=JSON.stringify(this.frm5.trains);
        }
        // step6
        let _awards=[];
        if(_data.awards.length){
          _data.awards.forEach((o,i)=>{
            let _item={
              award_name:o.award_name,
              award_desc:o.award_desc,
              issued_by:o.issued_by,
              get_at:o.get_at
            }
            _awards.push(_item)
          })
          this.frm6.awards=_awards;
          this.frm6.oldFrmData=JSON.stringify(_awards);
        }else{
          this.frm6.oldFrmData=JSON.stringify(this.frm6.awards);
        }
        // step7
        let _certifieds=[];
        if(_data.certifieds.length){
          _data.certifieds.forEach((o,i)=>{
            let _item={
              certified:o.certified,
              issued_by:o.issued_by,
              get_at:o.get_at,
              grade:o.grade||''
            }
            _certifieds.push(_item)
          })
          this.frm7.certifieds=_certifieds;
          this.frm7.oldFrmData=JSON.stringify(_certifieds);
        }else{
          this.frm7.oldFrmData=JSON.stringify(this.frm7.certifieds);
        }
      }
    },
    async getLevels(){
      let res = await educationLevel();
      if(res.code==200){
        this.levels=res.data;
      }
    },
    async getJobOption(){
      let res = await jobOption({type:1,pid:0});
      if(res.code==200){
          this.jobList=this.formatData(res.data,'all_sub_jobs');
      }
    },
    async getAreaList(){
      let res = await areaList({type:1,pid:0});
      if(res.code==200){
          this.areaList=this.formatData(res.data,'all_sub_areas');
      }
    },
    changeJobs(data,index){
      this.frm1.jobs[index].job1_id=data[0]
      this.frm1.jobs[index].job2_id=data[1]
      this.frm1.jobs[index].job3_id=data[2]
    },
    addJob(){
      this.frm1.jobs.push({job1_id:'',job2_id:'',job3_id:'',value:[]});
    },
    removeJob(item){
      var index = this.frm1.jobs.indexOf(item)
      if (index !== -1) {
        this.frm1.jobs.splice(index, 1)
      }
    },
    changeArea(data,index){
      this.frm1.areas[index].area1_id=data[0]
      this.frm1.areas[index].area2_id=data[1]
      this.frm1.areas[index].area3_id=data[2]
    },
    addAreas(){
      this.frm1.areas.push({area1_id:'',area2_id:'',area3_id:'',value:[]});
    },
    removeAreas(item){
      var index = this.frm1.areas.indexOf(item)
      if (index !== -1) {
        this.frm1.areas.splice(index, 1)
      }
    },
    gradeChange(value,tag){
      this.frm1[tag]=value;
    },
    formatData(data,sub){
      let _arry=[]
          data.forEach((o,i)=>{
            let _item={};
                _item.label=o.name;
                _item.value=o.id;
                o[sub].length&&(_item.children=[]);
                o[sub].length&&o[sub].forEach((j,k)=>{
                  let _item2={};
                      _item2.label=j.name;
                      _item2.value=j.id;
                      j[sub].length&&(_item2.children=[]);
                      j[sub].length&&j[sub].forEach((m,n)=>{
                        let _item3={};
                            _item3.label=m.name;
                            _item3.value=m.id;
                            _item2.children.push(_item3)
                      })
                      _item.children.push(_item2)
                })
                _arry.push(_item)
          })
          return _arry
    },
    checkCon(){
      this.frm1.introduce=$('#summernote').summernote('code');
      this.$refs.frm1.validateField('introduce');
    },
    // step 2
    addSkill(){
      this.frm2.skills.push({
        skill:'',
        experience:''
      });
    },
    removeSkill(item){
      var index = this.frm2.skills.indexOf(item)
      if (index !== -1) {
        this.frm2.skills.splice(index, 1)
      }
    },
    // step3
    addExp(){
      this.frm3.experiences.push({
          company:'',
          department:'',
          start_at:'',
          end_at:'',
          duty:'',
          job_content:''
      });
    },
    removeExp(item){
      var index = this.frm3.experiences.indexOf(item)
      if (index !== -1) {
        this.frm3.experiences.splice(index, 1)
      }
    },
    validateExp(rule, value, callback){
      let _i=rule.field.split('.')[1];
      let _end=this.frm3.experiences[_i].end_at;
      if(value === ''|| value==null || _end===''|| _end==null){
        callback('재직기간을 선택해주세요.')
      }else{
        if(new Date(value)<=new Date(_end)){
          callback('')
        }else{
          callback('재직기간을 다시한번 확인해주세요.')
        }
      }
    },
    // step4
    addEducation(){
      this.frm4.educations.push({
          school:'',
          status:'',
          end_at:'',
          specialities:''
      });
    },
    removeEducation(item){
      var index = this.frm4.educations.indexOf(item)
      if (index !== -1) {
        this.frm4.educations.splice(index, 1)
      }
    },
    // step5
    addTrains(){
      this.frm5.trains.push({
          training:'',
          training_organization:'',
          start_at:'',
          end_at:''
      });
    },
    removeTrains(item){
      var index = this.frm5.trains.indexOf(item)
      if (index !== -1) {
        this.frm5.trains.splice(index, 1)
      }
    },
    validateTrains(rule, value, callback){
      let _i=rule.field.split('.')[1];
      let _end=this.frm5.trains[_i].end_at;
      if(value === ''|| value==null || _end===''|| _end==null){
        callback('교육기간을 선택해주세요.')
      }else{
        if(new Date(value)<=new Date(_end)){
          callback('')
        }else{
          callback('교육기간을 다시한번 확인해주세요.')
        }
      }
    },
    // step6
    addAwards(){
      this.frm6.awards.push({
        award_name:'',
        issued_by:'',
        get_at:''
      });
    },
    removeAwards(item){
      var index = this.frm6.awards.indexOf(item)
      if (index !== -1) {
        this.frm6.awards.splice(index, 1)
      }
    },
    // step7
    addCertifieds(){
      this.frm7.certifieds.push({
        award_name:'',
        issued_by:'',
        get_at:''
      });
    },
    removeCertifieds(item){
      var index = this.frm7.certifieds.indexOf(item)
      if (index !== -1) {
        this.frm7.certifieds.splice(index, 1)
      }
    },
    // common
    changeStep(v){
      this.step=v;
    },
    handleScroll() {
      let _top=window.pageYOffset;
      if(_top>10){
        this.isFly=true
      }else{
        this.isFly=false
      }
    },
    showAvatarEdit(){
      this.setShowAvatarEdit(true)
    },
    formatBirthday(){
      try {
        let _arry=this.userInfo.birthday.split('-')
        return _arry[0]+'년 '+_arry[1]+'월 '+_arry[2]+'일생'
      } catch (error) {

      }
    },
    goBack(){
      this.dialogVisible=true
    },
    backCV(){
      this.$router.replace('/my/cv')
    },
    back(){
      this.step-=1;
    },
    next(){
      this.step+=1;
    },
  },
  destroyed(){
    window.removeEventListener('popstate', this.goBack, false);
    window.removeEventListener('scroll', this.handleScroll)
  },
  watch:{
    step(v){
      if(v==3&&this.levels.length==0){
        this.getLevels();
      }
    }
  }
}
</script>
<style lang="scss" scoped>
 @import "@/assets/styles/cv_manager.scss";
</style>
